/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package clienteddns;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author roberto
 */
class MinhaThread extends Thread {

    private String servidor;
    private String ipI;
    private String email;
    private String hostname;
    private String senha;
    private TrayIcon trayIcon;
    private SystemTray tray;
    private Frame atualizaHost;
    private Boolean ok = true;
    private String http = new String();
    Image icon;
    int s = 0;

    public String getHttp() {
        return http;
    }

    public void setHttp(String http) {
        this.http = http;
    }

    public MinhaThread(Frame atualizaHost) {
        this.atualizaHost = atualizaHost;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getHostname() {
        return hostname;
    }

    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    public String getIpI() {
        return ipI;
    }

    public void setIpI(String ipI) {
        this.ipI = ipI;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public String getServidor() {
        return servidor;
    }

    public void setServidor(String servidor) {
        this.servidor = servidor;
    }

    private void createSystemTray() {

//criando a classe que gerencia a bandeja
        if (!SystemTray.isSupported()) {
            System.err.println("Não é possível rodar a aplicação");
            System.exit(0);
        }
        tray = SystemTray.getSystemTray();
//icone que será exibido na bandeja
        icon = Toolkit.getDefaultToolkit().createImage(getClass().getResource("ok.gif").getPath());

        PopupMenu menu = new PopupMenu();

//item para sair
        MenuItem itemSair = new MenuItem("Sair");
        itemSair.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        menu.add(itemSair);

/*
        MenuItem itemAbrir = new MenuItem("Abrir");
        itemAbrir.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                tray.remove(trayIcon);
                atualizaHost.dispose();
                AtualizaHost a = new AtualizaHost();
                a.setHttp(getHttp());
                ok = false;
                a.setVisible(true);
            }
        });
        menu.add(itemAbrir);
*/
        trayIcon = new TrayIcon(icon, "Aplicação DDNS", menu);
        try {
//adiciona na bandeja do sistemaok
            tray.add(trayIcon);
            //exibindo um "tooltip" para o tray
            trayIcon.displayMessage("DDNS", "Sua aplicação está rodando", TrayIcon.MessageType.INFO);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private Boolean atualizar() throws InterruptedException, AWTException {
        ClienteDDNS c = new ClienteDDNS();
        try {
            URL url = new URL(getHttp()+"://" + servidor + "/cgi-bin/si.cgi?serviceType=1&email=" + email + "&password=" + senha + "&hostName=" + hostname + "&ip=" + ipI);
            c.registerMyHostnameVerifier();
            InputStreamReader inputReader = new InputStreamReader(url.openStream());
            BufferedReader bufferedReader = new BufferedReader(inputReader);
            String r = c.getValue(bufferedReader);
            if (r.equals("atualizado com sucesso")) {
                JOptionPane.showMessageDialog(null, "Atualizado com Sucesso", "Atualizado com Sucesso", JOptionPane.INFORMATION_MESSAGE);
                if(s==1){
                    
                    icon = Toolkit.getDefaultToolkit().createImage(getClass().getResource("ok.gif").getPath());
                    trayIcon.setImage(icon);
                    tray.remove(trayIcon);
                    tray.add(trayIcon);
                    trayIcon.displayMessage("DDNS", "Atualização voltou normalmente", TrayIcon.MessageType.INFO);
                    System.out.println("ok");
                    s=0;
                }
            } else {
                TimeUnit.SECONDS.sleep(5);
                atualizaHost.dispose();
                AtualizaHost a = new AtualizaHost();
                a.setVisible(true);
                a.setHttp(getHttp());
                return false;
            }
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
            if(s!=1){
                
                icon = Toolkit.getDefaultToolkit().createImage(getClass().getResource("erro.gif").getPath());
                trayIcon.setImage(icon);
                tray.remove(trayIcon);
                tray.add(trayIcon);
                trayIcon.displayMessage("DDNS", "Erro na atualização", TrayIcon.MessageType.INFO);
                System.out.println("erro");
                s=1;
            }
        }

        return true;
    }

            
    
    
    
    public void run() {
            try {
                    createSystemTray();
                    ok=true;
                while (ok) {
                    //TimeUnit.SECONDS.sleep(15);
                    System.out.println("aki"+ok);
                    Thread.sleep(5000);
                try {
                    ok = atualizar();
                } catch (AWTException ex) {
                    Logger.getLogger(MinhaThread.class.getName()).log(Level.SEVERE, null, ex);
                    break;
                }
                }
            }catch (InterruptedException ex) {
                // precisa fazer nada aqui
            }
    }
}
    
